package cn.xiaohello.UDP;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * UDP客户端编程中发送数据的实现.
 * 
 * @author XIAO
 *
 */
public class DataSocketTestClient {

	public static void main(String[] args) {
		// 客户端发送的消息
		String message = "Hello,I am client.";

		// 创建一个客户端链接
		DatagramSocket socket = null;
		try {
			socket = new DatagramSocket();
			System.out.println("客户机准备发送数据。。。");
			// 服务器ip
			String host = "127.0.0.1";
			int port = 80;

			// 将服务器IP转换为InetAddress对象
			InetAddress address = InetAddress.getByName(host);
			// 将要发送的消息转为byte数组
			byte[] b = message.getBytes();

			// 构造发送的数据包对象
			DatagramPacket packet = new DatagramPacket(b, b.length, address,
					port);
			socket.send(packet);

			// 构建消息缓存数组
			byte[] data = new byte[1024];
			packet = new DatagramPacket(data, data.length);
			// 接收服务器发来的数据
			socket.receive(packet);
			// 获得缓存数组中的内容
			b = packet.getData();
			System.out.println("服务器发来的数据：" + new String(b, 0, b.length));

		} catch (IOException e) {
			// TODO Auto-generated catch block
		} finally {
			socket.close();
		}
	}

}
